package com.objcat.servicesecurity.config;

import com.objcat.servicesecurity.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * ClassName: SecurityConfig
 * Description: security配置类
 *
 *
 * Java 代码中配置用户名密码
 * (也可在application配置,
 * spring.security.user.name=javaboy
 * spring.security.user.password=123)
 *
 * 详细教程见:
 * https://zhuanlan.zhihu.com/p/47584036
 *
 * <p>
 * date: 2020/7/28 10:51
 *
 * @author misheep
 * @since JDK 1.8
 */

@Slf4j
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BackdoorAuthenticationProvider backdoorAuthenticationProvider;
    @Autowired
    MyAccessDecisionManager myAccessDecisionManager;
    @Autowired
    MySecurityMetadataSource mySecurityMetadataSource;
    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    @Qualifier("userServiceImpl")
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        log.info("---进入 configure第一个方法----------------");
        //加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        /**
         * 下面这两行配置表示在内存中配置了两个用户
         * 如：在内存中创建一个名为javaboy的用户，密码为"123“，拥有admin权限，密码使用BCryptPasswordEncoder加密
         */
        log.info(passwordEncoder.encode("111"));
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("javaboy").roles("USER").password(passwordEncoder.encode("123"))
                .and()
                .withUser("lisi").roles("USER","ADMIN").password(passwordEncoder.encode("122"));
        //将自定义验证类注册进去
        auth.authenticationProvider(backdoorAuthenticationProvider);
        //加入数据库验证类，下面的语句实际上在验证链中加入了一个DaoAuthenticationProvider
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 设置忽略拦截
     * 直接过滤掉该地址，即该地址不走 Spring Security 过滤器链
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //将项目中静态资源路径开放出来
        web.ignoring().antMatchers( "/index.html", "/static/**", "/favicon.ico"
                ,"/error","/login_p","/css/**","/img/**","/js/**","/fonts/**","/config/**");
    }

    /**
     * 匹配 "/","/index" 路径，不需要权限即可访问
     * 匹配 "/user" 及其以下所有路径，都需要 "USER" 权限
     * 匹配 "/admin" 及其以下所有路径，都需要 "ADMIN" 权限
     * 登录地址为 "/login"，登录成功默认跳转到页面 "/user"
     * 退出登录的地址为 "/logout"，退出成功后跳转到页面 "/login"
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("---进入 configure第二个方法----------------");
        http
                .authorizeRequests()
                //以下无需security验证
//                .antMatchers("/","/index","/error").permitAll()
                //以下为接口对应的权限
//                .antMatchers("/user/**").hasRole("USER")
//                .antMatchers("/admin/**").hasRole("ADMIN")
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        //资源匹配（获得资源可访问角色信息）
                        object.setSecurityMetadataSource(mySecurityMetadataSource);
                        //匹配访问?
                        object.setAccessDecisionManager(myAccessDecisionManager);
                        return object;
                    }
                })
                .and()
                .formLogin().loginPage("/login_p").loginProcessingUrl("/login").permitAll()
                //1.自定义参数名称，与login.html中的参数对应
                .usernameParameter("myusername").passwordParameter("mypassword")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
                //以下无需security验证

//                .and()
//                //登录成功默认界面
//                .formLogin().loginPage("/login").defaultSuccessUrl("/user")
//                //1.自定义参数名称，与login.html中的参数对应
//                .usernameParameter("myusername").passwordParameter("mypassword")
//                .and()
//                //退出登录默认
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
//                .and()
//                //跨域保护
//                .csrf().disable()
//                //异常处理
//                .exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
    }
}
